package com.lantosec.hmrp.modules.supplier.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lantosec.hmrp.core.config.InitDataListener;
import com.lantosec.hmrp.core.kit.PageVO;
import com.lantosec.hmrp.core.util.UUIDUtils;
import com.lantosec.hmrp.modules.supplier.entity.SupplierContract;
import com.lantosec.hmrp.modules.supplier.entity.SupplierContractDetail;
import com.lantosec.hmrp.modules.supplier.entity.SupplierDir;
import com.lantosec.hmrp.modules.supplier.mapper.SupplierContractMapper;
import com.lantosec.hmrp.modules.supplier.service.ISupplierContractDetailService;
import com.lantosec.hmrp.modules.supplier.service.ISupplierContractService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lantosec.hmrp.modules.supplier.vo.SupplierContractVO;
import com.lantosec.hmrp.modules.uploads.entity.SysUploads;
import com.lantosec.hmrp.modules.uploads.service.ISysUploadsService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.context.annotation.Primary;
import lombok.extern.log4j.Log4j2;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.lantosec.hmrp.core.util.BeanUtils.entity2VO;

/**
 * <p>
 * 供应商合同 服务实现类
 * </p>
 *
 * @author AutoCode
 * @since 2020-06-21
 */
@Service
@Primary
@Log4j2
public class SupplierContractServiceImpl extends ServiceImpl<SupplierContractMapper, SupplierContract> implements ISupplierContractService {
    @Autowired
    private ISupplierContractDetailService iSupplierContractDetailService;

    @Autowired
    private ISysUploadsService iSysUploadsService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveSupplierContract(SupplierContractVO vo) {
        if(null != vo){
            SupplierContract supplierContract = vo.convertToEntity();
            supplierContract.setContractId(UUIDUtils.get());
            //判断供应商是手工录入还是选择 supplier_id为空时是手工录入
            if(StringUtils.isEmpty(vo.getSupplierCode())){
                //新增供应商及厂家目录
                String supplierId = saveSupplierDir(vo.getSupplierName());
                supplierContract.setSupplierCode(supplierId);
            }
            //新增供应商合同信息
            this.save(supplierContract);
            //新增供应商合同明细
            List<SupplierContractDetail> supplierContractDetails = vo.getSupplierContractDetails();
            if(CollectionUtils.isNotEmpty(supplierContractDetails)){
                supplierContractDetails.forEach(param->{
                    param.setContractId(supplierContract.getContractId());
                    iSupplierContractDetailService.save(param);
                });
            }
        }
    }

    /**
     * 新增供应商及厂家目录
     * @param supplierName
     */
    @Override
    public String saveSupplierDir(String supplierName) {
        //当为手工录入时需增加数据到supplier_dir表
        //查询表中最大的supplierId
        SupplierDir supplierDir = new SupplierDir();
        String supplierId = baseMapper.getSupplierDirMax();
        if(StringUtils.isEmpty(supplierId)){
            supplierDir.setSupplierId("SUP0001");
        }else {
            Integer s = Integer.parseInt(supplierId.substring(3))+1;
            //Integer型自动补零
            String supplierIds = String.format("%0"+4+"d", s);
            supplierDir.setSupplierId("SUP" + supplierIds);
        }
        supplierDir.setSupplier(supplierName);
        supplierDir.setManualFlag(1);
        baseMapper.saveSupplierDir(supplierDir);
        return supplierDir.getSupplierId();
    }

    @Override
    public PageVO<SupplierContractVO> getAll(PageVO<SupplierContract> page, String supplierCode) {
        PageVO<SupplierContractVO> supplierContractVOPageVO = new PageVO<>();
        //查询合同信息
        PageVO<SupplierContract> supplierContractPageVO = this.page(page, new QueryWrapper<SupplierContract>()
                .eq( SupplierContract.ColName.supplier_code.toString(), supplierCode));
        supplierContractVOPageVO = entity2VO(supplierContractPageVO);
        List<SupplierContractVO> supplierContracts = supplierContractVOPageVO.getRecords();
        supplierContracts.forEach(param -> {
            //查询合同信息的明细
            String contractId = param.getContractId();
            getSupplierContracts(param, contractId);

        });
        return supplierContractVOPageVO;
    }

    private void getSupplierContracts(SupplierContractVO param, String contractId) {
        List<SupplierContractDetail> supplierContractDetails = iSupplierContractDetailService.list(new QueryWrapper<SupplierContractDetail>()
                .eq(SupplierContractDetail.ColName.contract_id.toString(), contractId));
        param.setSupplierContractDetails(supplierContractDetails);
        //返回合同扫描件的路径
        if (StringUtils.isNotEmpty(param.getContractScan())) {
            List<Map> scanPathList = new ArrayList<>();
            String[] contractScan = param.getContractScan().split(",");
            for (int i = 0; i < contractScan.length; i++) {
                SysUploads sysUploads = iSysUploadsService.getById(contractScan[i]);
                String contractScanPath = InitDataListener.uploadsUrl + sysUploads.getSavePath() + sysUploads.getFileName();
                Map<String, String> attachPathMap = new HashMap<>();
                attachPathMap.put("name", sysUploads.getUploadTitle());
                attachPathMap.put("uploadId", sysUploads.getUploadId());
                attachPathMap.put("url", contractScanPath);
                scanPathList.add(attachPathMap);
            }
            param.setScanPathList(scanPathList);
        }
        //返回合同附件的路径
        if (StringUtils.isNotEmpty(param.getContractAttach())) {
            List<Map> attachPathList = new ArrayList<>();
            String[] contractAttach = param.getContractAttach().split(",");
            for (int i = 0; i < contractAttach.length; i++) {
                SysUploads sysUploads = iSysUploadsService.getById(contractAttach[i]);
                String contractAttachPath = InitDataListener.uploadsUrl + sysUploads.getSavePath() + sysUploads.getFileName();
                Map<String, String> attachPathMap = new HashMap<>();
                attachPathMap.put("name", sysUploads.getUploadTitle());
                attachPathMap.put("uploadId", sysUploads.getUploadId());
                attachPathMap.put("url", contractAttachPath);
                attachPathList.add(attachPathMap);
            }
            param.setAttachPathList(attachPathList);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateSupplierContract(SupplierContractVO vo) {
        SupplierContract supplierContract = vo.convertToEntity();
        //判断供应商是手工录入还是选择 supplier_id为空时是手工录入
        if(StringUtils.isEmpty(vo.getSupplierCode())){
            String supplierId = saveSupplierDir(vo.getSupplierName());
            supplierContract.setSupplierCode(supplierId);
        }
        this.updateById(supplierContract);
        //新增或者修改供应商合同明细
        //先删除
        baseMapper.deleteDetail(supplierContract.getContractId());
        List<SupplierContractDetail> supplierContractDetails = vo.getSupplierContractDetails();
        supplierContractDetails.forEach(param->{
            param.setContractId(supplierContract.getContractId());
            iSupplierContractDetailService.save(param);
        });
    }

    @Override
    public List<SupplierDir> getSupplierAll(String supplier) {
        return baseMapper.getSupplierAll(supplier);
    }

    @Override
    public SupplierContractVO getParamById(String id) {
        SupplierContractVO supplierContract = this.getById(id).convertToVO();
        //查询合同明细
        getSupplierContracts(supplierContract, id);
        return supplierContract;
    }
}
